<template>
    <el-tree-select v-model="selectedKeys" :data="treeData" multiple :render-after-expand="false" show-checkbox
        style="width: 240px" :props="treeProps" placeholder="请选择模版分类" node-key="id" @check="handleCheck" />
</template>

<script>
export default {
    props: {
        data: Object,
    },
    data() {
        return {
            selectedKeys: [],
            treeData: [],
            treeProps: {  // 新增树形配置
                label: 'title',
                children: 'children'
            },
            show: false
        }
    },
    async created() {
        const res = await $.get({
            url: '/do/list/tem_category_all',
            data: { pageSize: 300 }
        })
        this.treeData = this.buildTree(res || [])
    },

    methods: {
        buildTree(nodes) {
            const nodeMap = new Map();
            const tree = [];
            // 创建节点映射
            nodes.forEach(node => {
                nodeMap.set(node.id, { ...node, children: [] });
            });
            // 构建树结构
            nodeMap.forEach(node => {
                if (node.parentId === '0') {
                    tree.push(node);
                } else if (nodeMap.has(node.parentId)) {
                    const parent = nodeMap.get(node.parentId);
                    parent.children.push(node);
                } else {
                    tree.push(node);
                }
            });
            return tree;
        },
        handleCheck(checkedNode, { checkedKeys }) {
            this.selectedKeys = [...checkedKeys]
            this.$emit('update:modelValue', this.selectedKeys)
        },

    }
}
</script>
